package org.atlantis.grosbeak.cable.template;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用于渲染一个文件的模板。（通常用于文件下载）
 * 
 * @author <a href="mailto:seenoevil.cn@gmail.com">SeeNoEvil</a>
 * 
 */
public class FileTemplate implements Template {

	private File file;

	public FileTemplate(File file) {
		this.file = file;
	}

	public FileTemplate(String filePath) {
		this.file = new File(filePath);
	}

	public void render(ServletContext sc, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (file == null || !file.exists() || !file.isFile()
				|| file.length() > Integer.MAX_VALUE) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}
		String mime = sc.getMimeType(file.getName());
		mime = (mime == null) ? "application/octet-stream" : mime;
		response.setContentType(mime);
		response.setContentLength((int) file.length());
		InputStream ips = null;
		try {
			ips = new BufferedInputStream(new FileInputStream(file));
			OutputStream ops = response.getOutputStream();
			byte[] buffer = new byte[1024 * 3];
			int n = 0;
			while ((n = ips.read(buffer)) != -1) {
				ops.write(buffer, 0, n);
			}
			ops.flush();
			ops.close();
		} finally {
			if (ips != null) {
				ips.close();
			}
		}
	}
}
